<template>
  <div class="volunteer-teams">
    <!-- 我的队伍列表 -->
    <el-card class="teams-card" v-loading="loading.teams">
      <template #header>
        <div class="card-header">
          <h3>我的队伍</h3>
          <el-button type="primary" @click="showJoinTeamDialog">
            加入新队伍
          </el-button>
        </div>
      </template>

      <el-empty v-if="teams.length === 0" description="您还没有加入任何队伍" />

      <div v-else class="teams-grid">
        <el-row :gutter="20">
          <el-col v-for="team in teams" :key="team.id" :span="8">
            <div class="team-card">
              <div class="team-header">
                <el-image 
                  :src="team.avatar || 'https://placeholder.com/80'" 
                  class="team-avatar"
                  fit="cover" />
                <div class="team-badges">
                  <el-tag v-if="team.isVerified" type="primary" effect="dark" size="small">
                    官方认证
                  </el-tag>
                  <el-tag v-if="team.role === 'leader'" type="success" effect="dark" size="small">
                    队长
                  </el-tag>
                </div>
              </div>

              <div class="team-info">
                <h4 class="team-name">{{ team.name }}</h4>
                <p class="team-desc">{{ team.description }}</p>

                <div class="team-stats">
                  <div class="stat-item">
                    <div class="stat-value">{{ team.memberCount || 0 }}</div>
                    <div class="stat-label">成员</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-value">{{ team.activityCount || 0 }}</div>
                    <div class="stat-label">活动</div>
                  </div>
                  <div class="stat-item">
                    <div class="stat-value">{{ team.totalHours || 0 }}</div>
                    <div class="stat-label">总时长</div>
                  </div>
                </div>

                <div class="team-tags">
                  <el-tag
                    v-for="tag in team.tags"
                    :key="tag"
                    size="small"
                    effect="plain">
                    {{ tag }}
                  </el-tag>
                </div>

                <div class="team-actions">
                  <el-button type="primary" link @click="viewTeamDetail(team)">
                    查看详情
                  </el-button>
                  <el-button 
                    v-if="team.role === 'leader'"
                    type="success" 
                    link 
                    @click="manageTeam(team)">
                    管理队伍
                  </el-button>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>

    <!-- 加入队伍对话框 -->
    <el-dialog
      v-model="joinTeamDialogVisible"
      title="加入新队伍"
      width="600px">
      <div class="search-teams" v-loading="loading.search">
        <el-input
          v-model="searchKeyword"
          placeholder="搜索队伍名称..."
          class="search-input"
          clearable>
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>

        <div class="search-results">
          <el-empty 
            v-if="searchKeyword && searchResults.length === 0" 
            description="未找到相关队伍" />
            
          <div 
            v-for="team in searchResults" 
            :key="team.id" 
            class="search-item">
            <el-image 
              :src="team.avatar || 'https://placeholder.com/50'" 
              class="team-avatar"
              fit="cover" />
            <div class="team-info">
              <h4>{{ team.name }}</h4>
              <p>{{ team.description }}</p>
              <div class="team-meta">
                <span>{{ team.memberCount || 0 }} 名成员</span>
                <span>{{ team.activityCount || 0 }} 个活动</span>
              </div>
            </div>
            <el-button type="primary" @click="handleJoinTeam(team)">
              申请加入
            </el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { 
  getVolunteerTeams, 
  getTeamDetail, 
  joinTeam 
} from '@/api/volunteer-dashboard'

const router = useRouter()
const teams = ref([])
const joinTeamDialogVisible = ref(false)
const searchKeyword = ref('')
const searchResults = ref([])
const currentPage = ref(1)
const pageSize = ref(10)

// 加载状态
const loading = ref({
  teams: false,
  search: false
})

// 获取我的队伍列表
const fetchMyTeams = async () => {
  loading.value.teams = true
  try {
    const res = await getVolunteerTeams({
      page: currentPage.value,
      pageSize: pageSize.value,
      mine: true
    })
    teams.value = res.data.items
  } catch (error) {
    console.error('获取我的队伍失败', error)
    ElMessage.error('获取我的队伍失败')
  } finally {
    loading.value.teams = false
  }
}

// 搜索可加入的队伍
const searchTeams = async () => {
  if (!searchKeyword.value.trim()) {
    searchResults.value = []
    return
  }
  
  loading.value.search = true
  try {
    const res = await getVolunteerTeams({
      keyword: searchKeyword.value,
      mine: false
    })
    searchResults.value = res.data.items
  } catch (error) {
    console.error('搜索队伍失败', error)
    ElMessage.error('搜索队伍失败')
  } finally {
    loading.value.search = false
  }
}

// 监听搜索关键词变化
watch(searchKeyword, () => {
  searchTeams()
})

// 显示加入队伍对话框
const showJoinTeamDialog = () => {
  joinTeamDialogVisible.value = true
  searchKeyword.value = ''
  searchResults.value = []
}

// 查看队伍详情
const viewTeamDetail = (team) => {
  router.push(`/volunteer/teams/${team.id}`)
}

// 管理队伍
const manageTeam = (team) => {
  router.push(`/volunteer/teams/${team.id}/manage`)
}

// 申请加入队伍
const handleJoinTeam = async (team) => {
  try {
    await joinTeam(team.id)
    ElMessage.success(`已申请加入${team.name}，请等待审核`)
    joinTeamDialogVisible.value = false
    fetchMyTeams() // 刷新队伍列表
  } catch (error) {
    console.error('申请加入队伍失败', error)
    ElMessage.error('申请加入队伍失败')
  }
}

// 初始化
onMounted(() => {
  fetchMyTeams()
})
</script>

<style scoped lang="scss">
.volunteer-teams {
  .teams-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      h3 {
        margin: 0;
        font-size: 16px;
        font-weight: 600;
      }
    }
  }

  .teams-grid {
    .team-card {
      background: white;
      border-radius: 12px;
      overflow: hidden;
      box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
      margin-bottom: 20px;
      transition: all 0.3s ease;

      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
      }

      .team-header {
        position: relative;
        height: 100px;
        background: linear-gradient(135deg, #409EFF 0%, #36D1DC 100%);

        .team-avatar {
          position: absolute;
          left: 20px;
          bottom: 0;
          transform: translateY(50%);
          width: 80px;
          height: 80px;
          border-radius: 8px;
          border: 4px solid white;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
        }

        .team-badges {
          position: absolute;
          top: 12px;
          right: 12px;
          display: flex;
          gap: 8px;
        }
      }

      .team-info {
        padding: 50px 20px 20px;

        .team-name {
          margin: 0 0 8px;
          font-size: 18px;
          font-weight: 600;
          color: #303133;
        }

        .team-desc {
          margin: 0 0 16px;
          font-size: 14px;
          color: #606266;
          line-height: 1.4;
          height: 40px;
          overflow: hidden;
          text-overflow: ellipsis;
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
        }

        .team-stats {
          display: flex;
          justify-content: space-around;
          margin-bottom: 16px;
          padding: 12px 0;
          border-top: 1px solid #ebeef5;
          border-bottom: 1px solid #ebeef5;

          .stat-item {
            text-align: center;

            .stat-value {
              font-size: 18px;
              font-weight: 600;
              color: #303133;
              line-height: 1;
              margin-bottom: 4px;
            }

            .stat-label {
              font-size: 12px;
              color: #909399;
            }
          }
        }

        .team-tags {
          margin-bottom: 16px;
          display: flex;
          flex-wrap: wrap;
          gap: 8px;
        }

        .team-actions {
          display: flex;
          justify-content: flex-end;
          gap: 12px;
        }
      }
    }
  }
}

.search-teams {
  .search-input {
    margin-bottom: 20px;
  }

  .search-results {
    max-height: 400px;
    overflow-y: auto;

    .search-item {
      display: flex;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid #ebeef5;

      &:last-child {
        border-bottom: none;
      }

      .team-avatar {
        width: 60px;
        height: 60px;
        border-radius: 8px;
        margin-right: 16px;
      }

      .team-info {
        flex: 1;

        h4 {
          margin: 0 0 8px;
          font-size: 16px;
          color: #303133;
        }

        p {
          margin: 0 0 8px;
          font-size: 14px;
          color: #606266;
        }

        .team-meta {
          font-size: 13px;
          color: #909399;

          span {
            margin-right: 16px;
          }
        }
      }
    }
  }
}
</style> 